/*
 * @Description: 命令按钮
 * @version: 1.0.0
 * @Author: YinJianFeng
 * @Date: 2024-04-08 13:33:45
 */
import {
  type BaseCommand,
  FeatureManager,
  Icon,
  log,
  useCommandManager,
} from '@amcax/base';
import { useUserSettingCustomer } from '@app-base/common/providers/userSettingProvider';
import { Tooltip } from 'antd';
import i18n from 'i18next';
import { useEffect, useState } from 'react';
import { StyledButton } from './styled';
import { isEmpty } from 'lodash';

interface IProps {
  cmd: BaseCommand;
  showLabel?: boolean;
  horizontal?: boolean;
  featureEnableCode?: string;
}

export function CmdButton({
  cmd,
  showLabel = true,
  horizontal = false,
  featureEnableCode = '',
}: IProps) {
  const { currentCmd, invokeCmd } = useCommandManager();
  useEffect(() => {
    log('CmdButton Init', cmd);
    cmd.subscribeDisabled?.(setDisabled);
  }, []);
  const [disabled, setDisabled] = useState(!!cmd.initialDisabled);

  const { hiddenCommandIds, currentEnvironment } = useUserSettingCustomer();
  // FeatureManager.isFeatureEnabled('product-measure') && <Comp> ----> <CmdButton featureEnableCode={xxx} />
  if (
    !isEmpty(featureEnableCode) &&
    !FeatureManager.isFeatureEnabled(featureEnableCode)
  ) {
    return <></>;
  }
  if (hiddenCommandIds?.[currentEnvironment]?.includes(cmd.id)) {
    return <></>;
  }
  return (
    <Tooltip
      title={!showLabel && cmd.label ? i18n.t(cmd.label) : undefined}
      placement='bottom'
    >
      <StyledButton
        hasIconAndLabel={cmd.icon && showLabel}
        horizontal={horizontal}
        highlight={currentCmd === cmd && !cmd.noHighlight}
        disabled={disabled}
        onClick={() => invokeCmd(cmd)}
        icon={
          cmd.icon && (
            <Icon
              name={cmd.icon}
              style={{
                fontSize: '24px',
                opacity: disabled ? 0.3 : 1,
              }}
            />
          )
        }
      >
        {showLabel && i18n.t(cmd.label)}
      </StyledButton>
    </Tooltip>
  );
}
